#!/user/bin/env python3
# -*- coding: utf-8 -*-
"""
--------------------------------------
    Author:     JiChao_Song
    Date  :     2021/12/1 21:23
    Desc  :
--------------------------------------
"""
import json
import time

from apiview_doc.decorator import api_doc
from django.http import JsonResponse, HttpResponseBadRequest
from django.shortcuts import render
from jsonrpcserver import dispatch
from rest_framework.decorators import api_view

from common.enums.response_enums import get_status_code
from common.utils.jwt_utils import AuthJwt
from person.tasks import add_rpc_log_task
from common.utils.log_utils import logger


@api_view(['POST'])
def RPCBaeAPIView(request):
    """
    @author:    JiChao_Song
    @desc:      RPC调用
    @date:      2021/11/30 15:54
    """
    username, userId = AuthJwt(request = request).get_user_id_and_username()
    data = request.body
    data_dict = json.loads(data)

    log_data = dict(
        startTime = int(time.time() * 1000),
        method = request.method,
        func_name = data_dict.get('method'),
        request_body = str(data_dict.get('params')),
        request_headers = str(request.headers),
        response_headers = '',
        operatorId = username,
        operatorName = userId,
    )

    logger.info(f'RPC请求参数 {data}')
    result = json.loads(dispatch(data))
    log_data['response_body'] = str(result)
    log_data['endTime'] = int(time.time() * 1000)
    log_data['operateTime'] = int(time.time() * 1000)
    add_rpc_log_task.delay(log_data)

    if result.get('error'):
        return JsonResponse(
            data = result,
            status = HttpResponseBadRequest.status_code,
            json_dumps_params = {"ensure_ascii": False}
        )
    return JsonResponse(
        data = result,
        json_dumps_params = {"ensure_ascii": False}
    )


def docs(request):

    context = api_doc()

    context['status_code'] = get_status_code()

    return render(request, 'apiview_doc/docs/index.html', context)